<?php
/*
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <payment@prestashop.com>
*  @copyright  2007-2011 PrestaShop SA
*  @version  Release: $Revision: 7197 $
*  @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

class PaymentControllerCore extends FrontController
{
	public $php_self = 'payment-form.php';
	public $ssl = true;

	public function preProcess()
	{
		parent::preProcess();

		if (Tools::isSubmit('submitMessage'))
		{
			$fileAttachment = NULL;
			if (isset($_FILES['fileUpload']['name']) AND !empty($_FILES['fileUpload']['name']) AND !empty($_FILES['fileUpload']['tmp_name']))
			{
				$extension = array('.png', '.jpeg', '.gif', '.jpg');
				$filename = uniqid().substr($_FILES['fileUpload']['name'], -5);
				$fileAttachment['content'] = file_get_contents($_FILES['fileUpload']['tmp_name']);
				$fileAttachment['name'] = $_FILES['fileUpload']['name'];
				$fileAttachment['mime'] = $_FILES['fileUpload']['type'];
			}
			
			$message = Tools::htmlentitiesUTF8(Tools::getValue('message'));
			$name = Tools::htmlentitiesUTF8(Tools::getValue('name'));
			$tel = Tools::htmlentitiesUTF8(Tools::getValue('tel'));
			$invoice = Tools::htmlentitiesUTF8(Tools::getValue('invoice'));
			$price = Tools::htmlentitiesUTF8(Tools::getValue('money'));
			$date = Tools::htmlentitiesUTF8(Tools::getValue('date'));
			$bank = Tools::htmlentitiesUTF8(Tools::getValue('bank'));
			$from_bank = Tools::htmlentitiesUTF8(Tools::getValue('from_bank'));
			$subject = Tools::htmlentitiesUTF8(Tools::getValue('subject'));
			
			if (!($email = trim(Tools::getValue('email'))) OR !Validate::isEmail($email)){
				$this->errors[] = Tools::displayError('Invalid e-mail address');
			}
			elseif (!($id_contact = (int)(Tools::getValue('id_contact'))) OR !(Validate::isLoadedObject($payment = new Contact((int)($id_contact), (int)(self::$cookie->id_lang))))){
				$this->errors[] = Tools::displayError('Please select a subject on the list.');
			}
			elseif (!empty($_FILES['fileUpload']['name']) AND $_FILES['fileUpload']['error'] != 0){
				$this->errors[] = Tools::displayError('An error occurred during the file upload');
			}
			elseif (!empty($_FILES['fileUpload']['name']) AND !in_array(substr($_FILES['fileUpload']['name'], -4), $extension) AND !in_array(substr($_FILES['fileUpload']['name'], -5), $extension)){
				$this->errors[] = Tools::displayError('Bad file extension');
			}
			else
			{
				if ((int)(self::$cookie->id_customer))
					$customer = new Customer((int)(self::$cookie->id_customer));
				else
				{
					$customer = new Customer();
					$customer->getByEmail($email);
				}

				$payment = new Contact($id_contact, self::$cookie->id_lang);

				if (!((
						$id_customer_thread = (int)Tools::getValue('id_customer_thread')
						AND (int)Db::getInstance()->getValue('
						SELECT cm.id_customer_thread FROM '._DB_PREFIX_.'customer_thread cm
						WHERE cm.id_customer_thread = '.(int)$id_customer_thread.' AND token = \''.pSQL(Tools::getValue('token')).'\'')
					) OR (
						$id_customer_thread = (int)Db::getInstance()->getValue('
						SELECT cm.id_customer_thread FROM '._DB_PREFIX_.'customer_thread cm
						WHERE cm.email = \''.pSQL($email).'\' AND cm.id_order = '.(int)(Tools::getValue('id_order')).'')
					)))
				{
					$fields = Db::getInstance()->ExecuteS('
					SELECT cm.id_customer_thread, cm.id_contact, cm.id_customer, cm.id_order, cm.id_product, cm.email
					FROM '._DB_PREFIX_.'customer_thread cm
					WHERE email = \''.pSQL($email).'\' AND ('.
						($customer->id ? 'id_customer = '.(int)($customer->id).' OR ' : '').'
						id_order = '.(int)(Tools::getValue('id_order')).')');
					$score = 0;
					foreach ($fields as $key => $row)
					{
						$tmp = 0;
						if ((int)$row['id_customer'] AND $row['id_customer'] != $customer->id AND $row['email'] != $email)
							continue;
						if ($row['id_order'] != 0 AND Tools::getValue('id_order') != $row['id_order'])
							continue;
						if ($row['email'] == $email)
							$tmp += 4;
						if ($row['id_contact'] == $id_contact)
							$tmp++;
						if (Tools::getValue('id_product') != 0 AND $row['id_product'] ==  Tools::getValue('id_product'))
							$tmp += 2;
						if ($tmp >= 5 AND $tmp >= $score)
						{
							$score = $tmp;
							$id_customer_thread = $row['id_customer_thread'];
						}
					}
				}
				
				$old_message = Db::getInstance()->getValue('
					SELECT cm.message FROM '._DB_PREFIX_.'customer_message cm
					WHERE cm.id_customer_thread = '.(int)($id_customer_thread).'
					ORDER BY date_add DESC');
				
				//if ($old_message == htmlentities($message, ENT_COMPAT, 'UTF-8'))
				//{
				//	self::$smarty->assign('alreadySent', 1);
				//	$payment->email = '';
				//	$payment->customer_service = 0;
				//}
				
				if (!empty($payment->email))
				{
					if (Mail::Send((int)(self::$cookie->id_lang), 'payment_frm', $subject, array(
															'{email}' => $email,
															'{name}' => ((self::$cookie->id_customer) ? $customer->firstname.' '.$customer->lastname : $name),
															'{tel}' => $tel,
															'{invoice}' => $invoice,
															'{price}' => $price,
															'{date}' => $date,
															'{bank}' => $bank,
															'{from_bank}' => $from_bank
														     ), $payment->email, $payment->name, $email, ((int)(self::$cookie->id_customer) ? $customer->firstname.' '.$customer->lastname : $name), $fileAttachment)
						AND Mail::Send((int)(self::$cookie->id_lang), 'payment_frm_form', Mail::l('Your message has been correctly sent'), array(
																					 '{name}' => (self::$cookie->id_customer) ? $customer->firstname.' '.$customer->lastname : $name,
																					 '{tel}' => $tel,
															'{invoice}' => $invoice,
															'{price}' => $price,
															'{date}' => $date,
															'{bank}' => $bank,
															'{from_bank}' => $from_bank), $email))
						self::$smarty->assign('confirmation', 1);
					else
						$this->errors[] = Tools::displayError('An error occurred while sending message.');
				}

				if ($payment->customer_service)
				{
					if ((int)$id_customer_thread)
					{
						$ct = new CustomerThread($id_customer_thread);
						$ct->status = 'open';
						$ct->id_lang = (int)self::$cookie->id_lang;
						$ct->id_contact = (int)($id_contact);
						if ($id_order = (int)Tools::getValue('id_order'))
							$ct->id_order = $id_order;
						if ($id_product = (int)Tools::getValue('id_product'))
							$ct->id_product = $id_product;
						$ct->update();
					}
					else
					{
						$ct = new CustomerThread();
						if (isset($customer->id))
							$ct->id_customer = (int)($customer->id);
						if ($id_order = (int)Tools::getValue('id_order'))
							$ct->id_order = $id_order;
						if ($id_product = (int)Tools::getValue('id_product'))
							$ct->id_product = $id_product;
						$ct->id_contact = (int)($id_contact);
						$ct->id_lang = (int)self::$cookie->id_lang;
						$ct->email = $email;
						$ct->status = 'open';
						$ct->token = Tools::passwdGen(12);
						$ct->add();
					}

					if ($ct->id)
					{
						$cm = new CustomerMessage();
						$cm->id_customer_thread = $ct->id;
						$cm->message = htmlentities($message, ENT_COMPAT, 'UTF-8');
						if (isset($filename) AND rename($_FILES['fileUpload']['tmp_name'], _PS_MODULE_DIR_.'../upload/'.$filename))
							$cm->file_name = $filename;
						$cm->ip_address = ip2long($_SERVER['REMOTE_ADDR']);
						$cm->user_agent = $_SERVER['HTTP_USER_AGENT'];
						if ($cm->add())
						{
							if (empty($payment->email))
								Mail::Send((int)(self::$cookie->id_lang), 'payment_frm_form', Mail::l('Your message has been correctly sent'), array(
																					 '{name}' => ((self::$cookie->id_customer) ? $customer->firstname.' '.$customer->lastname : $name),
																					 '{tel}' => $tel,
															'{invoice}' => $invoice,
															'{price}' => $price,
															'{date}' => $date,
															'{bank}' => $bank,
															'{from_bank}' => $from_bank), $email);
							self::$smarty->assign('confirmation', 1);
						}
						else
							$this->errors[] = Tools::displayError('An error occurred while sending message.');
					}
					else
						$this->errors[] = Tools::displayError('An error occurred while sending message.');
				}
				
				if (count($this->errors) > 1)
					array_unique($this->errors);
			}
		}
	}

	public function setMedia()
	{
		parent::setMedia();
		Tools::addCSS(_THEME_CSS_DIR_.'payment-form.css');
	}

	public function process()
	{
		parent::process();
		
		self::$smarty->assign('site_url', Tools::htmlentitiesutf8('http://'.$_SERVER['HTTP_HOST'].__PS_BASE_URI__));
		
		if (self::$cookie->isLogged())
		{
			$customer = new Customer((int)(self::$cookie->id_customer));
		}
		
		function random_password($len)
		{
			srand((double)microtime()*10000000);
			$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
			$ret_str = "";
			$num = strlen($chars);
			for($i = 0; $i < $len; $i++)
			{
				$ret_str.= $chars[rand()%$num];
				$ret_str.=""; 
			}
			return $ret_str; 
		}
		
		self::$smarty->assign(array(
			'errors' => $this->errors,
			'email' => $customer->email,
			'name' => $customer->firstname.' '.$customer->lastname,
			'tel' => $customer->phone,
			'captcha' => random_password(5),
			'message' => date('d/m/Y H:i:s'),
			'fileupload' => Configuration::get('PS_CUSTOMER_SERVICE_FILE_UPLOAD')
		));


		if ($id_customer_thread = (int)Tools::getValue('id_customer_thread') AND $token = Tools::getValue('token'))
		{
			$customerThread = Db::getInstance()->getRow('
			SELECT cm.* FROM '._DB_PREFIX_.'customer_thread cm
			WHERE cm.id_customer_thread = '.(int)$id_customer_thread.' AND token = \''.pSQL($token).'\'');
			self::$smarty->assign('customerThread', $customerThread);
		}

		self::$smarty->assign(array(
			'payments' => Contact::getContacts((int)(self::$cookie->id_lang)),
			'message' => date('d/m/Y H:i:s'),
		));
	}

	public function displayContent()
	{
		$_POST = array_merge($_POST, $_GET);
		parent::displayContent();
		self::$smarty->display(_PS_THEME_DIR_.'payment-form.tpl');
	}
}

